<?php
/**
 * Copyright (c) 2006, PORTALIER Julien
 *
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 *
 * @package      FeatherCMS
 * @subpackage   Labels
 * @copyright    Copyright (c) 2006, Julien PORTALIER
 * @link         http://julien.portalier.com
 * @license      http://www.opensource.org/licenses/lgpl-license.php The LGPL License
 */

require_once FEATHER.'models'.DS.'tag.php';

abstract class LabelModel extends TagModel
{
	public $recursiveFields  = 'label';
	public $tagName          = 'label';
	
	function setConditions($labels)
	{
		if (!is_array($labels))
			$labels = explode(',', $labels);
		
		if (count($labels) == 1)
		{
			// single label
			$this->Webcomic->conditions(array("{$this->name}.{$this->tagName}" => $labels));
		}
		else
		{
			// multi-labels
			$module = $this->{$this->moduleClass};
			$sql = $this->getSQL($labels);
			$module->conditions(array("{$module->name}.{$module->primaryKey}" => "-! IN ( $sql )"));
			$module->unbind(array('hasOne' => $this->name));
		}
	}
	
	function getSQL($labels)
	{
		if (!is_array($labels))
			$labels = explode(',', $labels);
		
		$module = $this->{$this->moduleClass};
		$db = $this->db;
		
		// prepares SQL query
		$_base = "SELECT %s ".
			" FROM {$module->table} AS ".$db->field($module->name).
			" LEFT JOIN {$this->table} AS ".$db->field($this->name).
			" ON ".$db->field("{$this->name}.{$module->foreignKey}")." = ".$db->field("{$module->name}.{$module->primaryKey}").
			" WHERE ".$db->field("{$this->name}.{$this->tagName}")." = %s";
		$sql = "SELECT ".$db->field("{$module->name}.{$module->primaryKey}").
			" FROM {$module->table} AS ".$db->field($module->name).
			" LEFT JOIN {$this->table} AS ".$db->field($this->name).
			" ON ".$db->field("{$this->name}.{$module->foreignKey}")." = ".$db->field("{$module->name}.{$module->primaryKey}").
			" WHERE ".$db->field("{$this->name}.{$this->tagName}")." = ".$db->value(array_shift($labels));
		$end = '';
		
		// creates SQL query
		foreach($labels as $label)
		{
			$label = trim($label);
			if (!empty($label))
			{
				$sql .= " AND ".$db->field("{$module->name}.{$module->primaryKey}")." IN ( ".
					sprintf($_base, $db->field("{$module->name}.{$module->primaryKey}"), $db->value($label));
				$end .= ' )';
			}
		}
		
		return $sql.$end;
	}
	
	function getRelated($labels)
	{
		if (!is_array($labels))
			$labels = explode(',', $labels);
		
		$module = $this->{$this->moduleClass};
		$this->conditions(array(
			"{$module->name}.{$module->primaryKey}" => "-! IN ( ".$this->getSQL($labels)." )",
			"{$this->name}.{$this->tagName}" => "-! NOT IN ( ".$this->db->values(&$labels)." )"
		));
		
		$rs = $this->cloud(null, 20);
		return $rs;
	}
}
?>